package com.wbao.dianniu.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.OptionsPickerView.OnOptionsSelectListener;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.adapter.UserInfoHolder;
import com.wbao.dianniu.adapter.WorkExperienceAdapter;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.MyListView;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.customView.PickerView;
import com.wbao.dianniu.customView.PickerView.onSelectListener;
import com.wbao.dianniu.data.ChildZone;
import com.wbao.dianniu.data.JobDetailData;
import com.wbao.dianniu.data.WorkExperienceData;
import com.wbao.dianniu.data.Zone;
import com.wbao.dianniu.listener.IJobDetailListener;
import com.wbao.dianniu.listener.IJobReleaseListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.JobDetailManager;
import com.wbao.dianniu.manager.JobReleaseManager;
import com.wbao.dianniu.update.WorkListChangeManager;
import com.wbao.dianniu.update.WorkListChangeManager.WorkChangedListener;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 简历编辑
 *
 * @author yejianjun
 */
public class JobEditActivity extends BaseActivity implements IJobReleaseListener, WorkChangedListener, IJobDetailListener {
    /**
     * 省数据
     */
    private ArrayList<String> provinceList = new ArrayList<>();
    /**
     * 市数据
     */
    private ArrayList<ArrayList<String>> cityList = new ArrayList<>();
    private OptionsPickerView pvOptions;
    //弹出选择对话框
    private Dialog dialog;
    private String strMoney = "";
    private String strYears = "";
    private String strXueli = "";
    private JobReleaseManager manager;
    //    private ImageView iv_head;
//    private TextView userName;
//    private TextView userLabel;
//    private ImageView sexIV;
//    private ImageView addV;
    private EditText tv_subject;
    private TextView tvSalary;
    private TextView tv_address;
    private TextView tvExperience;
    private TextView tvEducation;
    //	private TextView tvTryout;
    private Button releaseBtn;
    private Dialog pDialog;
    //	private String[] tryoutList = new String[]{"可试用","不可试用"};
    private TextView editJobExperience;
    private TextView addJobExperience;
    private MyListView mListView;
    private JobDetailManager detailManger;
    private String headPic = "";
    private WorkExperienceAdapter adapter;
    private List<WorkExperienceData> experienceList;
    //    private JobDetailData jobDetailData;
    private final int MAX_COUNT = 20;
    private WorkListChangeManager workListChangeManager;
    private UserInfoHolder holder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_job_edit, LayoutParams.MATCH_PARENT, android.widget.LinearLayout.LayoutParams.MATCH_PARENT);
        setTitleName(getResources().getString(R.string.edit_resume));
        ImageButton backButton = getBackView();
        backButton.setImageResource(R.drawable.cancel_res_icon);
        Button fbBtn = getRightTextButton();
        fbBtn.setText(getResources().getString(R.string.preview));
        fbBtn.setOnClickListener(this);
        init();
        initManger();
        initData();
    }

    private void initData() {
        experienceList = new ArrayList<WorkExperienceData>();
        adapter = new WorkExperienceAdapter(this, 1);
        adapter.setData(experienceList);
        mListView.setAdapter(adapter);
        setListViewHeightBasedOnChildren(mListView);
    }

    private void init() {
        holder = new UserInfoHolder();
        RelativeLayout rl_money = findViewById(R.id.relative_money);
        RelativeLayout rl_workArea = findViewById(R.id.relative_work_area);
        RelativeLayout rl_wrok_years = findViewById(R.id.relative_work_years);
        RelativeLayout rl_xueli = findViewById(R.id.relative_xueli);
        mListView = findViewById(R.id.work_experience_list);
        editJobExperience = findViewById(R.id.job_edit_button);
        addJobExperience = findViewById(R.id.add_job_experience);
        holder.headIV = findViewById(R.id.user_head);
        holder.nameTV = findViewById(R.id.user_name);
        holder.labelTV = findViewById(R.id.user_label);
        holder.sexIV = findViewById(R.id.user_sex);
        holder.partnerIV = findViewById(R.id.user_partner);
        holder.addV = findViewById(R.id.add_v_iv);
        if (!TextUtils.isEmpty(GlobalContext.getHeadPic())) {
            headPic = GlobalContext.getHeadPic();
            PictureDownloadUtils.displayHeadImage(this, holder.headIV, GlobalContext.getHeadPic());
        }
        holder.nameTV.setText(GlobalContext.getNiceName() == null ? "" : GlobalContext.getNiceName());
        holder.labelTV.setText(GlobalContext.getLabel() == null ? "" : GlobalContext.getLabel());
        Utils.showSex(this, GlobalContext.getSex(), holder.sexIV);
        if (GlobalContext.getIndustryAuthority()) {
            holder.addV.setVisibility(View.VISIBLE);
        } else {
            holder.addV.setVisibility(View.GONE);
        }


        tv_subject = findViewById(R.id.apply_job_name);
        tv_address = findViewById(R.id.job_area_tv);
        releaseBtn = findViewById(R.id.job_release_button);
        rl_money.setOnClickListener(this);
        rl_workArea.setOnClickListener(this);
        rl_wrok_years.setOnClickListener(this);
        rl_xueli.setOnClickListener(this);
        releaseBtn.setOnClickListener(new NoDoubleClickListener() {

            @Override
            public void onNoDoubleClick(View v) {
                apply();
            }
        });
        editJobExperience.setOnClickListener(this);
        addJobExperience.setOnClickListener(this);
        mListView.setClickable(false);
        tvSalary = findViewById(R.id.money_content_tv);
        tvExperience = findViewById(R.id.job_years_tv);
        tvEducation = findViewById(R.id.xueli_tv);
        // 取消收入设置提醒，
//        Utils.ContentLengthLimit(this, tv_subject, MAX_COUNT);
        setListener();
    }

    /**
     * 设置相关监听器-- 禁用enter键
     */
    private void setListener() {
        tv_subject.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });

    }


    private void initManger() {
        manager = new JobReleaseManager(this);
        manager.addJobReleaseListener(this);
        detailManger = new JobDetailManager(this);
        detailManger.addJobDetailListener(this);
        detailManger.jobDetail(GlobalContext.getAccountId(), GlobalContext.getAccountId());
        workListChangeManager = WorkListChangeManager.getInstance();
        workListChangeManager.addWorkChangeListener(this);
    }

    private View showRealase(int layoutId) {
        dialog = new Dialog(this, R.style.custom_Dialog);
        try {
            Window win = dialog.getWindow();
            win.getDecorView().setPadding(0, 0, 0, 0);
            win.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setAttributes(lp);
            win.setWindowAnimations(R.style.buttom_animation);
        } catch (Exception e) {
            e.printStackTrace();

        }
        View view = LayoutInflater.from(this).inflate(layoutId, null);
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();
        return view;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.relative_money:    //期望薪资
                // 隐藏键盘
                Utils.hideSoftInput(JobEditActivity.this, tv_subject);

                View viewMoney = showRealase(R.layout.job_release_money);
                PickerView pickerMoney = viewMoney.findViewById(R.id.picker_money);
                List<String> datas = new ArrayList<String>();
                String[] xinziStr = getResources().getStringArray(R.array.salary_array);
                for (int i = 0; i < xinziStr.length; i++) {
                    datas.add(xinziStr[i]);
                }
                pickerMoney.setData(datas);
                if ("".equals(strMoney)) {
                    strMoney = xinziStr[0];
                }
                pickerMoney.setOnSelectListener(new onSelectListener() {

                    @Override
                    public void onSelect(String text) {
                        // TODO Auto-generated method stub
                        strMoney = text;
                    }
                });
                Button confirmMoney = viewMoney.findViewById(R.id.job_money_confirm);
                confirmMoney.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        tvSalary.setText(strMoney);
                        if (null != dialog && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                });
                break;
            case R.id.relative_work_area:    //工作地区
                // 隐藏键盘
                Utils.hideSoftInput(JobEditActivity.this, tv_subject);

                initAreaData();
                break;
            case R.id.relative_work_years:        //工作经验
                // 隐藏键盘
                Utils.hideSoftInput(JobEditActivity.this, tv_subject);

                View viewYear = showRealase(R.layout.job_release_money);
                PickerView pickerYear = viewYear.findViewById(R.id.picker_money);
                List<String> datasYear = new ArrayList<String>();
                String[] experience = getResources().getStringArray(R.array.job_experience_array);
                for (int i = 0; i < experience.length; i++) {
                    datasYear.add(experience[i]);
                }
                pickerYear.setData(datasYear);
                if ("".equals(strYears)) {
                    strYears = experience[0];
                }
                pickerYear.setOnSelectListener(new onSelectListener() {

                    @Override
                    public void onSelect(String text) {
                        // TODO Auto-generated method stub
                        strYears = text;
                    }
                });
                Button confirmYear = viewYear.findViewById(R.id.job_money_confirm);
                confirmYear.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        tvExperience.setText(strYears);
                        if (null != dialog && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                });
                break;
            case R.id.relative_xueli:    //学历
                // 隐藏键盘
                Utils.hideSoftInput(JobEditActivity.this, tv_subject);

                View viewXueli = showRealase(R.layout.job_release_money);
                PickerView pickerXueli = viewXueli.findViewById(R.id.picker_money);
                List<String> datasXueli = new ArrayList<String>();
                String[] education = getResources().getStringArray(R.array.education_no_unlimited);
                for (int i = 0; i < education.length; i++) {
                    datasXueli.add(education[i]);
                }
                pickerXueli.setData(datasXueli);
                if ("".equals(strXueli)) {
                    strXueli = education[0];
                }
                pickerXueli.setOnSelectListener(new onSelectListener() {

                    @Override
                    public void onSelect(String text) {
                        strXueli = text;
                    }
                });
                Button confirmXueli = viewXueli.findViewById(R.id.job_money_confirm);
                confirmXueli.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        tvEducation.setText(strXueli);
                        if (null != dialog && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                });
                break;
            case R.id.right_button:    //预览
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putString(Const.BUNDLE_HEADPIC, headPic);
                bundle.putString(Const.BUNDLE_REALNAME, holder.nameTV.getText().toString().trim());
                bundle.putString(Const.BUNDLE_LABEL, holder.labelTV.getText().toString().trim());
                bundle.putInt(Const.INTENT_SEX, GlobalContext.getSex());
                bundle.putBoolean(Const.INTENT_IS_MESSAGE, GlobalContext.getIndustryAuthority());
                bundle.putString(Const.BUNDLE_SUBJECT, tv_subject.getText().toString().trim());
                bundle.putString(Const.BUNDLE_SALARY, tvSalary.getText().toString().trim());
                bundle.putString(Const.BUNDLE_ADDRESS, tv_address.getText().toString().trim());
                bundle.putString(Const.BUNDLE_EXPERIENCE, tvExperience.getText().toString().trim());
                bundle.putString(Const.BUNDLE_EDUCATION, tvEducation.getText().toString().trim());
                bundle.putString(Const.BUNDLE_CONTENT, Utils.WorkListDataToString(experienceList));
                intent.putExtra(Const.BUNDLE_DATA, bundle);
                intent.setClass(JobEditActivity.this, JobPreviewActivity.class);
                startActivity(intent);
                break;
            case R.id.job_edit_button:// 编辑工作经历
                Intent edit = new Intent();
                edit.setClass(JobEditActivity.this, EditJobExActivity.class);
                startActivity(edit);
                break;
            case R.id.add_job_experience:    // 添加工作经历
                Intent add = new Intent();
                add.setClass(JobEditActivity.this, AddJobExActivity.class);
                startActivity(add);
                break;
//		case R.id.job_release_button:// 发布
//			apply();
//			break;
            default:
                break;
        }

    }

    @Override
    public void onJobReleaseFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        Notification.toast(this, errorMsg);
    }

    @Override
    public void onJobReleaseSuccess() {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        Notification.toast(this, "发布成功");
        /**    修改简历完善状态 改成已完善	*/
//        GlobalContext.isPerfectResume = true;
        GlobalUserData userData = new GlobalUserData();
        userData.setPerfectResume(true);
        finish();
    }

    /**
     * 地区选择器
     */
    private void initAreaData() {
        //选项选择器
        pvOptions = new OptionsPickerView(this);
        InputStream input = getResources().openRawResource(R.raw.zone);
        String jsonData = Utils.inputStream2String(input, "utf-8");
        List<Zone> zoneList = JsonUtil.toObjectList(jsonData, Zone.class);
        for (Iterator iterator = zoneList.iterator(); iterator.hasNext(); ) {
            Zone zone = (Zone) iterator.next();
            provinceList.add(zone.getName());
            LinkedList<ChildZone> linkList = zone.getChildrens();
            ArrayList<String> arrayList = new ArrayList<String>();
            for (int i = 0; i < linkList.size(); i++) {
                arrayList.add(linkList.get(i).getName());
            }
            cityList.add(arrayList);
        }

        pvOptions.setPicker(provinceList, cityList, true);
        pvOptions.setTitle(getResources().getString(R.string.city_selected));
        pvOptions.setCyclic(false);

        pvOptions.setSelectOptions(0, 0);
        pvOptions.setOnoptionsSelectListener(new OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                if (option2 >= cityList.get(options1).size()) { // 快速滑动时，最后一个超过界限，则显示最后一个
                    option2 = cityList.get(options1).size() - 1;
                }
                String areaStr = provinceList.get(options1) + cityList.get(options1).get(option2);
                tv_address.setText(areaStr);
            }
        });
        pvOptions.show();
    }

    private void apply() {
        if (TextUtils.isEmpty(tv_subject.getText().toString().trim())) {
            Notification.toast(this, "选择应聘岗位");
            tv_subject.requestFocus();
            return;
        } else if (TextUtils.isEmpty(tvSalary.getText().toString())) {
            Notification.toast(this, "选择薪资");
            tvSalary.requestFocus();
            return;
        } else if (TextUtils.isEmpty(tv_address.getText().toString())) {
            Notification.toast(this, "选择工作地区");
            tv_address.requestFocus();
            return;
        } else if (TextUtils.isEmpty(tvExperience.getText().toString())) {
            Notification.toast(this, "选择工作经验");
            tvExperience.requestFocus();
            return;
        } else if (TextUtils.isEmpty(tvEducation.getText().toString())) {
            Notification.toast(this, "选择学历");
            tvEducation.requestFocus();
            return;
        }
        /*if(TextUtils.isEmpty(tvTryout.getText().toString())){
            Notification.toast(this, "选择是否可试用");
			tvTryout.requestFocus();
			return;
		}*/
        pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
        pDialog.show();
        manager.jobRelease(GlobalContext.getAccountId(), tv_subject.getText().toString().trim(), tvSalary.getText().toString().trim(), tvExperience.getText().toString().trim(), tvEducation.getText().toString().trim(), tv_address.getText().toString().trim());
    }

    @Override
    public void workAddChanged(WorkExperienceData data) {
        experienceList.add(data);
//		adapter.setData(experienceList);
        setListViewHeightBasedOnChildren(mListView);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void workRemoveChanged(int position) {
        experienceList.remove(position);
//		adapter.setData(experienceList);
        setListViewHeightBasedOnChildren(mListView);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onJobDetailFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onJobDetailSuccess(JobDetailData data) {
        if (null != data) {
            display(data);
//            jobDetailData = data;
        }
    }

    private void display(JobDetailData data) {
        if (!TextUtils.isEmpty(data.getHeadPic())) {
            headPic = data.getHeadPic();
            PictureDownloadUtils.displayHeadImage(this, holder.headIV, data.getHeadPic());
        }
        holder.nameTV.setText(data.getRealName() == null ? "" : data.getRealName());
        holder.labelTV.setText(data.getLabel() == null ? "" : data.getLabel());
        Utils.showSex(this, data.getUserInfo().sex, holder.sexIV);
        Utils.showPartner(this, data.getUserInfo().partner, holder.partnerIV);
        Utils.showAuth(data.getUserInfo(), holder.addV);
        if (!TextUtils.isEmpty(data.getPost())) {
            tv_subject.setText(data.getPost());
        }
        if (!TextUtils.isEmpty(data.getSalary())) {
            tvSalary.setText(data.getSalary());
        }
        if (!TextUtils.isEmpty(data.getAddress())) {
            tv_address.setText(data.getAddress());
        }
        if (!TextUtils.isEmpty(data.getExperience())) {
            tvExperience.setText(data.getExperience());
        }
        if (!TextUtils.isEmpty(data.getEducation())) {
            tvEducation.setText(data.getEducation());
        }
        if (!TextUtils.isEmpty(data.getDescribe())) {
            experienceList = Utils.parseWorkData(data.getDescribe());
            adapter.setData(experienceList);
            setListViewHeightBasedOnChildren(mListView);
            adapter.notifyDataSetChanged();
        }
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter   
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目   
            View listItem = adapter.getView(i, null, listView);
            // 计算子项View 的宽高   
            listItem.measure(0, 0);
            // 统计所有子项的总高度   
            totalHeight += listItem.getMeasuredHeight();
        }

        LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度   
        // params.height最后得到整个ListView完整显示需要的高度   
        listView.setLayoutParams(params);
    }

    @Override
    public void workModifyChanged(int id, WorkExperienceData data) {
        for (int i = 0; i < experienceList.size(); i++) {
            if (id == experienceList.get(i).getId()) {
                experienceList.get(i).setPost(data.getPost());
                experienceList.get(i).setStartDate(data.getStartDate());
                experienceList.get(i).setEndDate(data.getEndDate());
                experienceList.get(i).setContent(data.getContent());
                break;
            }
        }
//		adapter.setData(experienceList);
        setListViewHeightBasedOnChildren(mListView);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        } else if (null != pvOptions && pvOptions.isShowing()) {
            pvOptions.dismiss();
        } else {
            super.onBackPressed();
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if (null != workListChangeManager) {
            workListChangeManager.removeWorkChangeListener(this);
        }
        if (null != manager) {
            manager.removeJobReleaseListener(this);
        }
        if (null != detailManger) {
            detailManger.removeJobDetailListener(this);
        }

    }
}
